package com.avocado.base.validator.organization;

import com.avocado.base.repository.OrganizationRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

@Slf4j
public class OrganizationEditCodeValidator implements ConstraintValidator<OrganizationEditCodeValidation, Object> {
    private String field1;
    private String field2;

    private final OrganizationRepository organizationRepository;

    public OrganizationEditCodeValidator(OrganizationRepository organizationRepository) {
        this.organizationRepository = organizationRepository;
    }

    @Override
    public void initialize(OrganizationEditCodeValidation constraintAnnotation) {
        this.field1 = constraintAnnotation.field1();
        this.field2 = constraintAnnotation.field2();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {


        try {

            Object field1Value = PropertyUtils.getProperty(value, field1);

            Object field2Value = PropertyUtils.getProperty(value, field2);

            Long id=(Long)field1Value;

            String code=(String)field2Value;

            long count=organizationRepository.getCountByCodeAndExcludeId(code,id);

            return count<1L;



        } catch (Exception ex) {
            log.error(ex.getLocalizedMessage());
        }
        return false;
    }
}
